
from random import randint


def read_file():
    f = open('user.txt')
    data = f.read()
    data_list = data.split(" ")
    f.close()
    data_dict = {data_list[0]: data_list[1:4]}
    return data_dict


def output(data):
    user_name = ''
    game_times = ''
    fastest = ''
    all_times = ''
    for key in data:
        user_name = key
        game_times = int(data[key][0])
        fastest = int(data[key][1])
        all_times = int(data[key][2])

    if game_times != 0:
        average = all_times / game_times
        print("%s，你已经玩了%d次，最少%d轮猜出答案，平均%s轮猜出答案" % (user_name, game_times, fastest, '%.2f' % float(average)))

    return user_name, game_times, fastest, all_times


def write_file(user_name, game_times, fastest, all_times):
    out = open('user.txt', 'w')
    s = ""
    s = user_name + " " + str(game_times) + " " + str(fastest) + " " + str(all_times)

    out.write(s)
    out.close()


def guess(user_name, game_times, fastest, all_times):
    # 总游戏次数加一
    game_times = game_times + 1

    # 一次游戏过程
    guess_num = randint(1, 100)
    times = 0
    while True:
        a = int(input("请猜一个 1 - 100 的数字："))
        times += 1
        if a < guess_num:
            print("猜小了，再试试")
        elif a > guess_num:
            print("猜大了，再试试")
        else:
            print("猜对了，你一共猜了%d轮" % times)
            break

    # 更新猜过的总轮数
    all_times = all_times + times

    # 更新最快猜出的轮数
    if fastest == 0:
        fastest = times
    elif times < fastest:
        fastest = times

    # 更新平均轮数
    average = all_times / game_times

    # 打印游戏数据
    print("%s，你已经玩了%d次，最少%d轮猜出答案，平均%s轮猜出答案" % (user_name, game_times, fastest, '%.2f' % float(average)))

    game = input('是否继续游戏（输入y继续，其他退出）：')
    if game == 'y':
        # 游戏数据写入文件
        write_file(user_name, game_times, fastest, all_times)
        print("退出游戏，欢迎下次再来")
    else:
        guess(user_name, game_times, fastest, all_times)


def start():
    data = read_file()
    user_name, game_times, fastest, all_times = output(data)
    # 开始游戏
    guess(user_name, game_times, fastest, all_times)


start()
